package com.bjtime.hprinter.lib;


import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bjtime.hprinter.R;
import com.bjtime.hprinter.ui.DesignerActivity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ConnectionActivity extends AppCompatActivity {
    private static final int REQUEST_BLUETOOTH_CODE = 0X0001;
    private LoBaseAdapter<BlueToochBean> mBlueAdapter;
    private BluetoothDevice device;
    private ListView mLvblue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connection);
        mLvblue =  findViewById(R.id.lv_blueTooch);
       DesignerActivity.Companion.getBluetoothAdapter().cancelDiscovery();
        DesignerActivity.Companion.getBluetoothAdapter().startDiscovery();
       Toast.makeText(ConnectionActivity.this, "开始扫描", Toast.LENGTH_SHORT).show();
       initData();

    }


    private void initData() {
        //创建一个IntentFilter对象，将其action指定为BluetoothDevice.ACTION_FOUND,查找蓝牙
        IntentFilter intentFileter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        //注册广播接收器
        registerReceiver(mReceiver, intentFileter);



        mBlueAdapter = new LoBaseAdapter<BlueToochBean>(this, mBlueList, R.layout.item_bluetooch) {
            @Override
            public void bindData(int position, ViewHolder holder, int mPosition) {
                TextView buleTooth = (TextView) holder.findViewById(R.id.blueName);//打印机名称
                TextView selBule = (TextView) holder.findViewById(R.id.sel_blue);//打印机状态（已连接）
                selBule.setText("");
                buleTooth.setText(String.format("%s\n%s", mBlueList.get(position).getmName(), mBlueList.get(position).getmAdress()));
            }
        };
        mLvblue.setAdapter(mBlueAdapter);
        mLvblue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //判断打印机是否已经连接 如果已经连接 提示是否断开连接
                TextView tvState = (TextView) view.findViewById(R.id.sel_blue);
                String state = tvState.getText().toString().trim();
                if (state.length() == 0) {
                    TextView buleTooth = (TextView) view.findViewById(R.id.blueName);//打印机名称
                    String[] temp = buleTooth.getText().toString().split("\n");

                    //写入本地缓存
                    SharedPreferences sharedPreferences = getSharedPreferences("defaultprinterinfo", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                    editor.putString("name", temp[0]);
                    editor.putString("address", temp[1].toUpperCase());
                    editor.commit();//提交修改
                    DesignerActivity.Companion.setPrintName(temp[0]);
                    DesignerActivity.Companion.setPrintMacAddress(temp[1].toUpperCase());



                    //选择打印机
                    setResult(RESULT_OK);
                    //Toast.makeText(ConnectionActivity.this, "已连接打印机:" + CurrentLabel.lb.printerInfo.pritnerName, Toast.LENGTH_SHORT).show();
                    ConnectionActivity.this.finish();
                } else {
                }
            }
        });
    }

    private List<BlueToochBean> mBlueList = new ArrayList<BlueToochBean>() {
        @Override
        public boolean contains(Object o) {
            BlueToochBean blueToochBean = (BlueToochBean) o;
            Iterator<BlueToochBean> it = this.iterator();
            while (it.hasNext()) {
                if (it.next().getmAdress().equals(blueToochBean.getmAdress())) {
                    return true;
                }
            }
            return false;
        }
    };
    BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //得到intent里面的信息
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device == null) return;
                String deviceName = device.getName();
                if (deviceName == null) return;
                Log.d("9999", deviceName);
                //排除机型
                if (!device.getName().toLowerCase().startsWith("pt"))
                    return;

                BlueToochBean bean = new BlueToochBean();
                bean.setmAdress(device.getAddress());
                bean.setmName(device.getName());
                if (!mBlueList.contains(bean)) {
                    mBlueList.add(bean);
                    mBlueAdapter.notifyDataSetChanged();
                }
            } else if (intent.getAction().equals(
                    "android.bluetooth.device.action.PAIRING_REQUEST")) {
                Log.i("tag11111", "ddd");

            }
        }
    };
    @Override
    protected void onDestroy() {
        if (DesignerActivity.Companion.getBluetoothAdapter() != null) {
            DesignerActivity.Companion.getBluetoothAdapter().cancelDiscovery();
        }
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

}
